<?php
/**
 * Created by PhpStorm.
 * User: idcu
 * Date: 2016/3/1
 * Time: 13:08
 */
namespace Admin\Model;
use IDCU\Model\RelationModel;

class UnitModel extends RelationModel
{
    protected $_validate = array(
        array('no','require','单元编号必填',1,'regex',3),
        array('building_id','require','楼ID缺失',1,'regex',3),
//        array('name','require','必填',1,'regex',3),
        array('no','/^\d$/','单元编码格式不正确',0,'regex',1),
        array('no,building_id','checkNo1','单元编码已存在',0,'callback',1),
        array('no,id,building_id','checkNo2','单元编码已存在',0,'callback',2)
    );

    protected $_auto = array(
    );

    protected $_link = array(
        'Community' => array(
            'mapping_type' => self::BELONGS_TO,
            'class_name' => 'Community',
            'mapping_name' => 'community',
            'foreign_key' => 'community_id'
        ),
        'Zone' => array(
            'mapping_type' => self::HAS_MANY,
            'class_name' => 'Zone',
            'mapping_name' => 'zone',
            'foreign_key' => 'zone_id'
        ),
        'Building' => array(
            'mapping_type' => self::HAS_MANY,
            'class_name' => 'Building',
            'mapping_name' => 'building',
            'foreign_key' => 'building_id'
        ),
        'Room' => array(
            'mapping_type' => self::HAS_MANY,
            'class_name' => 'Room',
            'mapping_name' => 'rooms',
            'foreign_key' => 'unit_id'
        ),
    );

    public function _before_write(&$data)
    {
        parent::_before_write($data); // TODO: Change the autogenerated stub
        if($data['building_id']){
            $building = D('Building')->find($data['building_id']);
            $data['full_parent_name'] = $building['full_parent_name'].$building['name'];
            $data['community_id'] = $building['community_id'];
            $data['zone_id'] = $building['zone_id'];
            if($data['no']){
                $data['no'] = $building['no'].$data['no'];
            }
        }
    }

    public function _after_insert($data, $options)
    {
        parent::_after_insert($data, $options); // TODO: Change the autogenerated stub
        M('Building')->where(array('id'=>$data['building_id']))->setInc('children_count',1);
    }

    function checkNo1($param){
        $units = $this->field('no')->where(array('building_id' => $param['building_id']))->select();
        foreach($units as $k=>$v){
            if(substr($v['no'],-1) == $param['no']){
                return false;
            }
        }
        return true;
    }

    function checkNo2($param){
        $units = $this->field('no')->where(array('building_id' => $param['building_id'],'id'=>array('neq',$param['id'])))->select();
        foreach($units as $k=>$v){
            if(substr($v['no'],-1) == $param['no']){
                return false;
            }
        }
        return true;
    }
}
